import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import { queryCurrentUser } from './services/login';
import logo from '../public/logo.svg';

// const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: LoginTyping.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<LoginTyping.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

// 请求前拦截
const authHeaderInterceptor = (url: string, options: any) => {
  const authHeader = {
    Authorization:
      'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdGFmZklkIjo5NSwiY2lkIjo3LCJ1c2VyaWQiOiJhaXIiLCJpYXQiOiIyMDIxLTEyLTMxVDA5OjI0OjA4LjQ0MVoifQ==.0C1ihdoKrvrabJsSQDmVqvAgZbxxrc3BCtgeCdl4Qbg=',
  };
  return {
    url: `${url}`,
    options: { ...options, interceptors: true, headers: authHeader },
  };
};

export const request: RequestConfig = {
  // responseInterceptors: [demoResponseInterceptors],
  requestInterceptors: [authHeaderInterceptor],
};

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    logo: <img src={logo} />,
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    onPageChange: () => {
      // const { location } = history;
      // 如果没有登录，重定向到 login
      // if (!initialState?.currentUser && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }
    },
    breakpoint: false,
    defaultCollapsed: false,
    menuHeaderRender: undefined,
    collapsedButtonRender: false,
    splitMenus: true,
    layout: 'mix',
    headerTheme: 'light',
    disableMobile: true,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态

    ...initialState?.settings,
  };
};
